<?php

/**
 * Presenter pro prihlaseni a odhlaseni uzivatele
 *
 * @author David Dusek
 */

use \Nette\Application\UI,
    \Nette\Security as NS;

class LoginPresenter extends AdminPresenter {
    /** @persistent */
    public $backlink = '';
    
    public function startup() {
        parent::startup();
        
        $this->setLayout('_' . $this->globalConfig["loginLayout"]);
    }
    
    public function renderDefault() {
        ;
    }

    /**
     * Prihlasovaci formular se jmenem a heslem.
     * @return \Nette\Application\UI\Form prihlasovaci formular
     */
    protected function createComponentLoginForm() {
        $form = new UI\Form();

        $form->addText("username", $this->translate("username"))
                ->setRequired($this->translate("requiredErr"));

        $form->addPassword("password", $this->translate("password"))
                ->setRequired($this->translate("requiredErr"));

        $form->addSubmit("login", $this->translate("login"));

        $form->onSuccess[] = callback($this, 'loginFormSubmitted');
        
        return $form;
    }
    
    public function loginFormSubmitted($form) {
        try {
            $values = $form->getValues();
            
            
            $this->getUser()->setExpiration('+ 2 hours', FALSE);
            
            $this->getUser()->login($values->username, $values->password);
            $this->restoreRequest($this->backlink);
            $this->redirect(':User:User:');
        } catch (NS\AuthenticationException $e) {
            $form->addError($e->getMessage());
        }
    }
    
    /**
     * Odhlaseni uzivatele a presmerovani na obrazovku pro prihlaseni. 
     */
    public function actionLogout() {
        $this->user->logout();
        $this->redirect(":User:Login:");
    }
}
